$(function(){
	phoneSlider();
})
function phoneSlider(){
	//移动终端滑动 滚动
	if(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch){
		(function(){
			//mbct 为menuBarDom的scrollTop
			var startPosition,movePositon,endPosition,mbct,mbcH,scrH;
			var touchDom = document.getElementById("scrHeight");
			var menuBarDom = document.getElementById("menuBar");
			//滑块dom
			var scrSliderDom = document.getElementById("scrSlider");
			touchDom.addEventListener("touchstart",tstart,false);
			
			function tstart(e){
				var touch = e.touches[0]; //获取第一个触点
				startPosition = {
					x:touch.pageX, //页面触点X坐标
					y:touch.pageY //页面触点Y坐标
				};
				//menuBar的scrollTop的值
				mbct = menuBarDom.scrollTop;
				//menuBar的scrollHeight的高度值
				mbcH = menuBarDom.scrollHeight;
				//touchDom的offsetHeight的高度值
				scrH = touchDom.scrollHeight;
				touchDom.addEventListener("touchmove",tmove,false);
				touchDom.addEventListener("touchend",tend,false);
			};
			
			function tmove(e){
				e.preventDefault();
				var touch = e.touches[0]; //获取第一个触点
				movePositon = {
					x:touch.pageX, //页面触点X坐标
					y:touch.pageY //页面触点Y坐标	
				};
				
				var ySpace = movePositon.y-startPosition.y; 
				
				var mt = mbct - ySpace
				menuBarDom.scrollTop = mt;
				//滑块的margintop的值
				var per = mt / (mbcH - scrH);
				//alert(per+"==="+ mt +"=="+ mbcH +"=="+ scrH +"=="+per  *  (scrH - scrSliderDom.offsetHeight ) )
				var t = per  *  (scrH - scrSliderDom.offsetHeight );
				if(t<0){
					t=0;
				}else if(t> scrH - scrSliderDom.offsetHeight ){
					t = scrH - scrSliderDom.offsetHeight;
				}
			//	alert(t);
				scrSliderDom.style.top = t + "px";
			//	alert(scrH+"==="+ mbct +"=="+ mbcH +"=="+ ySpace)
				
				
			};
			
			function tend(){
				
				touchDom.removeEventListener("touchmove",tmove,false);
				touchDom.removeEventListener("touchend",tend,false);
			}
		})();
	};
};


//#slider的滚动条
var scrH_temp = 0;
var scrH,menuH,sliderH,percent;
//左侧菜单栏滚动
function slideScroll(){
	$("#scrHeight").on("mouseenter",function(){
		scrH = $("#menuBar").get(0).scrollHeight;
		menuH = $("#menuBar").height();
		if(scrH > menuH){
			$("#scrHeight .scrBar").height(menuH);
			percent = menuH / scrH;
			sliderH = menuH * percent;
			$("#scrHeight .scrSlider").height(sliderH);
			$("#scrHeight .scrBar").fadeIn();
		};
	})
	.on("mousemove",function(){
		scrH = $("#menuBar").get(0).scrollHeight;
		if(scrH != scrH_temp && (scrH > menuH)){
			scrH_temp = scrH;
			percent = menuH / scrH;
			sliderH = menuH * percent;
			$("#scrHeight .scrSlider").height(sliderH);
			$("#scrHeight .scrBar").fadeIn();
			//鼠标滚轮事件
			$("#scrHeight").on("mousewheel DOMMouseScroll",function(e){
				e.preventDefault();
				var oEv = e.originalEvent;
				var wheelRange = oEv.wheelDelta ? - oEv.wheelDelta/120 : (oEv.detail || 0)/3;
				var step = 10;
				var t = wheelRange * step + $("#menuBar").scrollTop();
				var st = t * ( menuH - sliderH ) / ( scrH - menuH );
				if(st< 0){
					st = 0;
				}else if( st > (menuH - sliderH)){
					st = menuH - sliderH;
				};
				$("#menuBar").scrollTop(t);
				$("#scrHeight .scrSlider").stop(true,true).animate({"top":st})
			});
		}else if(scrH <= menuH){
			$("#scrHeight .scrBar").fadeOut();
		};
	})
	.on("mouseleave",function(){
		$("#scrHeight .scrBar").fadeOut();
	});
	
	//滚动条的拖动
	document.getElementById("scrSlider").onmousedown = function(e){
		var dom = this;
		var totH = document.getElementById("scrBar").clientHeight;
		var scrollH = $(dom).outerHeight();
		var maxH = totH - scrollH ; //最大可拖动垂直高度
		var ev = e || window.event ;
		ev.preventDefault();
		ev.stopPropagation();
		var pos = getXY(ev);
		var x = pos.x;
		var y = pos.y
		var l = dom.offsetLeft;
		var t = dom.offsetTop;
		var dleft,dtop;
		document.onmousemove = function(e){
			var evv = e || window.event;
			evv.preventDefault();
			evv.stopPropagation();
			dleft = getXY(evv).x - x + l;
			dtop = getXY(evv).y - y + t;
			if (dtop<0)dtop = 0;		//上边界控制
			if(dtop>maxH)dtop = maxH;	//下边界控制
			$(dom).css({
				"top":dtop
			});
			$("#menuBar").scrollTop(dtop);
		}
		document.onmouseup = function(){
			document.onmousemove = null;	//解除鼠标移动事件
			document.onmouseup = null;		//解除鼠标弹出事件
		}
	}	
	//移出document绑定的事件
	document.getElementById("scrSlider").onmouseleave = function(e){
		document.onmousemove = null;	//解除鼠标移动事件
		document.onmouseup = null;		//解除鼠标弹出事件
	}
}

var tabnav_width = 0; //记录tabnav的宽度
var iframe_h = 0; //iframe的高度
var iframe_time = "";
var mainIframeMark = false;
var tabIndex = 1;
var PADDING_WIDTH = 32;	//页签的左右padding值和border的值
var excutabnav_width = 60;
var clickIndex = 0; //记录当前页签的索引
/*
 * openArr = {
 * 	title:打开页面的标题名
 * 	url:打开页面的url
 * 	width:宽度 + 30页签的padding值
 * }
 * **/
var openArr = [];

function firstLoad_initParams(){
	var _this = $("#menuBar>li:first");
	url = _this.find("a").data("url");
	title = $.trim(_this.find(".icon_name").text());
	width = _this.find(".icon_name").width();
	openArr.push({
		title: title,
		url: url,
		width: width + PADDING_WIDTH
	})
}

//获取已打开所有页签的总宽度
function getOpenIframeWidth(arr,cb){
	var width = 0;
	for(var i = 0;i<arr.length;i++){
		width += arr[i].width
	}
	cb&&cb(width);
	return width;
}

//maxWidth最大的宽度，index为需要显示的索引对应的数据
function getMaxIndex(arr,maxWidth,index,cb){
	var width = 0;
	var newIndex = 0;
	if(index < arr.length){
		width = arr[index].width;
		for(var i=0;i<arr.length;i++){
			width += arr[i].width
			if(i != index && width >= maxWidth){
				newIndex = i - 1;
				cb&&cb(newIndex);
				return newIndex
			}
		}
	}
	return newIndex;
}

function getShowIndex(els,cb){
	var index = 0;
	var mark = false
	els.each(function(n,obj){
		if($(obj).hasClass('active')){
			index = n;
			return false;
		}
	})
	cb&&cb(index);
	return index;
}

//index前显示，index后隐藏,showIndex显示
function tabShowAndHide(els,index,showIndex){
	for(var i= 0; i<els.length;i++){
		if(i<index){
			els.eq(i).show();
		}else{
			els.eq(i).hide();
		}
	}
	if(showIndex){
		els.eq(showIndex).show();
	}
}

function initTabShowOrHide(){
	//alert(index)
	getOpenIframeWidth(openArr,function(width){
		if(tabnav_width - width - excutabnav_width <= 0){
			//打开的页签的总长度 加上 其他（折叠）的长度 大于 总长度
			getShowIndex($("#tabnav_l>li"),function(showindex){
				getMaxIndex(openArr,tabnav_width - excutabnav_width,showindex,function(tabShowIndex){
					$("#excutabnav").show();
					tabShowAndHide($("#tabnav_l>li"),tabShowIndex,showindex);
				});
			});
		}else{
			$("#excutabnav").hide();
			tabShowAndHide($("#tabnav_l>li"),openArr.length);
		}
	});
}

//判断是否打开了，没有则返回-1，有则返回对应的index值
function hasOpened(title,arr){
	var len = arr.length;
	for(var i= 0;i<len;i++){
		var obj = arr[i];
		if(obj.title == title && obj.title.length == title.length){
			return i
		}
	}
	return -1
}

//根据index打开对应的页面
function openTabPanl(index){
	$("#tabnav_l>li").eq(index).find("a").tab('show');
	var iframes = $("#tabnav_panl>.tab-pane").eq(index).find('iframe');
	iframes.attr('src',iframes.attr('src'));
}

//根据参数url判断新增或删除iframe
//有url,则表示新增序号为index的iframe
//无url,则表示删除序号为index的iframe
//tabnav_l 
function opIframe(index,url,title){
	if(url){
		$("#tabnav_l").append('<li><a href="#tab'+index+'" data-toggle="tab">'+ title +'<i class="glyphicon glyphicon-remove"></i></a></li>');
		$("#tabnav_panl").append('<div class="tab-pane active" id="tab'+ index +'"><iframe id="mainLayFrame'+ index +'" src="'+ url +'" width="100%" height="'+iframe_h+'" frameborder="0"></iframe></div>');
		$("#excutabnav ul").append('<li><a href="javascript:void(0);">'+ title +'<i class="glyphicon glyphicon-remove"></i></a></li>');
		$("#tabnav_l>li:last").find("a").tab('show');
		clickIndex = openArr.length;
	}else{
		var mark = $("#tabnav_l>li").eq(index).hasClass("active"); 
		if(mark){
			$("#tabnav_l>li").eq(index-1).find("a").tab("show");
			var title = openArr[index-1].title;
			$("#menuBar li").each(function(n){
				var menutitle = $.trim($(this).children('a').find(".icon_name").text());
				if(title == menutitle){
					munuBarSelected($(this));
					return false;
				}
			})
		}
		$("#tabnav_l>li").eq(index).remove();
		$("#tabnav_panl>.tab-pane").eq(index).remove();
		$("#excutabnav ul>li").eq(index).remove();
		openArr.splice(index,1);
		
		initTabShowOrHide();
	}
}
//左侧菜单栏添加选择状态
function munuBarSelected(obj){
	obj = $(obj);
	var menuBar = $('#menuBar li');
	var topMenu = $("#menuBar .collapse")
	if(obj.hasClass('selActive')){//一级菜单
		if(obj.hasClass('active')){
			return;
		}else{
			menuBar.removeClass('active');
			topMenu.collapse('hide')
			obj.addClass('active')
		}
	}else{//一级菜单
		if(obj.hasClass('active')){
			return;
		}else{
			if(!obj.parents('.collapse ').hasClass('in')){//该父菜单已展开
				topMenu.collapse('hide')
				obj.parents('.collapse').collapse('show');
			}
			menuBar.removeClass('active');
			obj.addClass('active')
		}
	}
}

function menuAddActive(title){
	$("#menuBar li").each(function(n){
		var menutitle = $.trim($(this).children('a').find(".icon_name").text());
		if(title == menutitle){
			munuBarSelected($(this));
			return false;
		}
	})
}
function initIndexLayout(){
	//初始化tabnav_width的宽度
	tabnav_width = $("#tabnav").outerWidth();
	//初始化变量openArr
	firstLoad_initParams();
	//初始化的函数
	initIframe();
	//初始化功能菜单旁的按钮样式
	//窗口改变时的事件
	$(window).resize(function(){
		clearTimeout(iframe_time);
		iframe_time = setTimeout(function(){
			tabnav_width = $("#tabnav").outerWidth();
			/*var tindex = getShowIndex($("#tabnav_l>li"));
			initTabShowOrHide(tindex);*/
			initIframe();
			//初始化功能菜单旁的按钮样式
		//	slideScroll();
		},500)
	});
}

$(function(){
	slideScroll();
	initIndexLayout();

	//点击左侧标签，在右侧添加tab页签，并使显示当前页签的内容
	$("#menuBar").on("click","li",function(event){
		var ev = event || window.event;
		var _this = $(this);
		var url;
		var title,width;
		var isOpen = $("#wtl_leftMenu").outerWidth() == 50 ?false:true;
		//点击的是一级菜单
		if(_this.hasClass("selActive")){
			url = _this.find("a").data("url");
			title = $.trim(_this.find(".icon_name").text());
			width = _this.find(".icon_name").width();
			if(url){
				var index = hasOpened(title,openArr);
				if(index == -1){
					openArr.push({
						title: title,
						url: url,
						width: width + PADDING_WIDTH
					})
					opIframe(tabIndex,url,title);
					tabIndex++;
				}else{
					openTabPanl(index);
				}
				_this.parents("#menuBar").find("li").removeClass("active");
				_this.parents("#menuBar").find(".collapse").collapse("hide");
				_this.addClass("active");
			}
		}else{//点击二级菜单
			ev.stopPropagation();
			url = _this.find("a").data("url");
			title = $.trim(_this.find(".icon_name").text());
			width = isOpen?_this.find(".icon_name").outerWidth():title.length * 12
			if(url){
				var index = hasOpened(title,openArr);
				if(index == -1){
					openArr.push({
						title: title,
						url: url,
						width: width + PADDING_WIDTH
					})
					opIframe(tabIndex,url,title);
					tabIndex++;
				}else{
					openTabPanl(index)
				}
				initTabShowOrHide();
				_this.siblings().removeClass("active");
				_this.parents("#menuBar").find("li").removeClass("active")
				_this.addClass("active");
			}
		}
	});
	
	//一级菜单
	$(document).on('hide.bs.collapse','.collapse', function () {
		//一级菜单折叠的dom操作
		var _this = $(this);
		var parSelLi = _this.parents(".selActive");
		if(parSelLi.find('.active').length){
			parSelLi.addClass('active')
		}else{
			parSelLi.removeClass('active')
		}
	})
	$(document).on('show.bs.collapse','.collapse',function(){
		//一级菜单展开的dom操作
		var _this = $(this);
		var parSelLi = _this.parents(".selActive");
		if(parSelLi.find('.active').length){
			parSelLi.removeClass('active')
		}else{
			parSelLi.removeClass('active')
		}
		//其他都折叠
		parSelLi.siblings().find(".collapse").collapse("hide");
	})
	
	//右侧页签的删除操作
	$(document).on('click','.glyphicon-remove',function(ev){
		ev.preventDefault();
		ev.stopPropagation();
		var title = $.trim($(this).parent().text());
		var index = hasOpened(title,openArr);
		opIframe(index);
	})
	//右侧页签的点击选择操作
	$(document).on('click','#tabnav_l > li a',function(){
		var title = $.trim($(this).text());
		menuAddActive(title);
	})
	
	$("#excutabnav").on('mouseleave',function(){
		$(this).find('.dropdown-toggle').dropdown('toggle')
	})
	
	//点击 #slider_btn 折叠展开
	$("#slider_btn").on("click",function(){
		if($(this).hasClass("isopen")){
			$("#wtl_leftMenu").animate({"width":180},function(){
				$("#menuBar").find("span.icon_name").show();
			});
			
			$("#menuBar .sub_li .icon_left ").animate({"width":45});
			$("#tab_list").animate({"margin-left":180});
			$(this).removeClass("isopen");
		}else{
			$("#menuBar").find("span.icon_name").hide();
			$("#wtl_leftMenu").animate({"width":50});
			$("#menuBar .sub_li .icon_left").animate({"width":32});
			$("#tab_list").animate({"margin-left":50});
			$(this).addClass("isopen");
		}
	})
	
	//右侧tips操作
	$("#menuBar").on("mouseenter","li>a",function(event){
		if($("#menuBar").width() > 60){
			return;
		}
		if(!$(".menu_tips").length){
			$("body").append("<div class='menu_tips'></div>");
		}
		var _top = getTop($(this).get(0));
		var _scrTop = $("#menuBar").scrollTop();
		var menu_tips = $(".menu_tips");
		var text = $(this).data("title");
		menu_tips.css({
			"top":_top - _scrTop
		});
		if(text){
			menu_tips.text(text);
			menu_tips.stop(true,false).fadeIn();
		}
	}).on("mouseleave","li>a",function(){
		$("body .menu_tips").stop(true,false).fadeOut();
	});
	
});
	
//获取js Dom对象距离文档顶部的距离
function getTop(obj){
	var ctop =0;
	while(obj){
		ctop += obj.offsetTop;
		obj = obj.offsetParent;
	}
	return ctop;
}

//初始化iframe高度
	
function initIframe(){
	
	//获取浏览器的可视高度
	var wh = $(window).innerHeight();
	//顶部高度
	var header_nav =  $("#wtl_nav").outerHeight();
	//底部高度
	var footer_h = $("#wtl_footer").outerHeight();
	//左侧slider_btn高度
	var slider_btn_h = $("#slider_btn").outerHeight();
	//右侧页签的高度
	var tabH = $("#tabnav").outerHeight();	
	iframe_h = wh - header_nav - footer_h - tabH;
	
	$("#wtl_con").css("height",iframe_h);
	//初始化iframe高度
	/*$("#tabnav_panl iframe").each(function(){
		$(this).css('height',iframe_h);
		$(this).contents().find('body').height(iframe_h);
	})*/
	$("#mainLayFrame").css({"height":iframe_h});
	$("#mainLayFrame").contents().find("body").height(iframe_h);
	//初始化MenuBar的高度
	$("#menuBar").css({"height":iframe_h - slider_btn_h + footer_h});
};


//清除商品分类、资源管理、数据字典存储的cookie信息
$(function(){
	$("#menuBar li").on("click",function(){
		setCookie("category_ztreeId","","","");//商品分类cookie
		setCookie("permissionZtreeId","","","");//资源管理cookie
		setCookie("dictionaries_ztreeId","","","");//数据字典cookie
		setCookie("orderDtlEditx","","","");
	})
});

function exOpIframe(tabIndex,url,title) {
	var index = hasOpened(title,openArr);
	if(index == -1){
		openArr.push({
			title: title,
			url: url,
			width: width + PADDING_WIDTH
		})
		opIframe(top.tabIndex,url,title);
		top.tabIndex++;
	}else{
		openTabPanl(index)
	}
	initTabShowOrHide();
	$("#menuBar").find("li").removeClass("active")
	$("#menuBar").find("li").eq(index).addClass("active");
	// opIframe(tabIndex,url,title)
}
